//域名
import { baseUrl } from '@/utils/baseUrl.js';

import { showTip } from '@/utils/utils.js';

function http(opts) {
  //加载过程
  uni.showLoading({
    title: '加载中',
    mask: true
  })
  let network;
  const token = opts.params && opts.params.token ? opts.params.token : uni.getStorageSync('token');
  const httpDefaultOpts = {
    url: opts.baseUrl ? opts.baseUrl + opts.url : baseUrl + opts.url,
    data: opts.params,
    method: opts.method,
    timeout: 20000,
    sslVerify: false,
    header: opts.method == 'GET' ? {
      'X-Requested-With': 'XMLHttpRequest',
      "Accept": "application/json",
      'content-Type': 'application/x-www-form-urlencoded'
    } : {
      'X-Requested-With': 'XMLHttpRequest',
      "Content-Type": "application/json; charset=UTF-8",
    },
    dataType: 'json',
  };

  if (token) {
    httpDefaultOpts.header.token = token;
  }

  return new Promise((resolve, reject) => {
    uni.getNetworkType({
      success: function (res) {
        network = res.networkType;
        if (res.networkType == 'none') {
          uni.showToast({
            title: '无网络',
            icon: 'none',
            duration: 5000
          });
        }
      }
    });

    uni.request(httpDefaultOpts).then(res => {
      if (res.statusCode == 200) {
        if (res.data.code == 401) {
          console.log('登录失效 token失效，请重新登录');
          expired();
        } else {
          resolve(res.data);
        }
      } else if (res.statusCode == 401) {
        expired();
      } else {
        showTip('服务器繁忙，请重试!');
        resolve(res.data);
      }
    }).catch(response => {
      reject(response);
    }).finally(() => {
      uni.hideLoading();
    });
  });
}

//请求接口
const requestSearchPort = (opts) => {
  opts.params = opts.params || {};
  return http(opts);
};

//登录失效
function expired() {
  uni.removeStorageSync('token');
  uni.removeStorageSync('userInfo');
  uni.hideLoading();
  uni.navigateTo({
    url: '/pages/login/login'
  });
}

export {
  requestSearchPort,
};